// 应用入口文件，初始化 Express 应用并挂载路由
// 引入 dotenv 库，加载 .env 文件
require("dotenv").config({ path: "./.env" });
const express = require("express");
const routes = require("./src/routes");
const morgan = require("morgan"); // 导入 morgan 中间件
const path = require("path");
const { initConfig } = require("./src/utils/init");
const IPBlacklistTool = require("./src/utils/IPBlacklistTool"); // 引入黑名单工具类
const R2Util = require("./src/utils/r2Util");
const SyncImages = require("./src/utils/r2SyncImages");
const {
  handleVerticalRequest,
  handleHorizontalRequest,
  handleAdaptiveRequest,
} = require("./src/controllers/pageController");
const app = express();

// 中间件处理 CORS 和公共逻辑
app.use((req, res, next) => {
  // 设置 CORS 头部
  res.set({
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
    "Access-Control-Allow-Headers": "Content-Type, Authorization, Accept",
    "Access-Control-Allow-Credentials": "true",
    "Access-Control-Max-Age": "86400", // 24小时
  });

  // 处理预检请求
  if (req.method === "OPTIONS") {
    return res.status(204).end();
  }

  next();
});

// 使用 morgan 中间件记录请求日志
app.use(morgan("combined")); // 'combined' 格式包含详细的日志信息

// 配置静态文件服务
app.use(express.static(path.join(__dirname, "src/public")));

//==============黑名单===========
if (process.env.IPBLACK_OPEN == 1) {
  // 每分钟最多请求30次，封禁时间8小时，黑名单最大1000个IP
  const ipBlacklistTool = new IPBlacklistTool(
    process.env.REQUEST_LIMIT_PERMINUTE,
    process.env.REQUEST_LIMIT_PERHOUR,
    process.env.BLOCK_TIME,
    1000
  );
  // 启用 trust proxy 配置
  ipBlacklistTool.enableTrustProxy(app);
  // 使用中间件处理IP请求
  app.use((req, res, next) => ipBlacklistTool.handleRequest(req, res, next));
}
//=================================

// 捕获所有未处理的错误
app.use((err, req, res, next) => {
  const time = new Date().toISOString();
  console.error(`[${time}] Error occurred: ${err.message}`);
  res.status(500).send("Something went wrong!");
});

//=================r2同步==========
if (process.env.R2_OPEN == 1) {
  const r2Util = new R2Util(
    process.env.R2_ACCESS_KEY_ID,
    process.env.R2_SECRET_ACCESS_KEY,
    process.env.R2_ENDPOINT
  );
  const syncImages = new SyncImages(r2Util, process.env.R2_BUCKET_NAME);
  syncImages.startSync();
}
//======================

//=========================调用次数统计=====================
const CallCountTracker = require("./src/utils/callCountTracker");
const tracker = CallCountTracker.getInstance(undefined);

app.use((req, res, next) => {
  tracker.recordCall(req.path);
  next();
});
//==============================================

app.use(express.json()); // 解析 JSON 请求体

// 新增页面路由
app.get("/vertical", handleVerticalRequest);
app.get("/horizontal", handleHorizontalRequest);
app.get("/adaptive", handleAdaptiveRequest);

app.use("/api", routes); // 挂载 API 路由

// 404 处理
app.use((req, res) => {
  res.status(404).send("Not Found");
});

// 设置监听端口
const PORT = process.env.PORT || 3000;

// 启动服务器
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);

  //初始化
  initConfig();
});

module.exports = app;
